'''
Sourced from some website (I dont remember which but this snippet pops up 
everywhere
'''

import os
import smtplib
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEAudio import MIMEAudio
from email.MIMEImage import MIMEImage
from email.Encoders import encode_base64

import config

##def check_config():
##    #TODO: Check the guser and gpwd
##    assert False

def send_mail(subject, text, *attachmentFilePaths):
    msg = MIMEMultipart()
    msg['From'] = config.get_guser()
    msg['To'] = config.get_backupemail()
    msg['Subject'] = subject
    msg.attach(MIMEText(text))

    for attachmentFilePath in attachmentFilePaths:
        msg.attach(get_attachment(attachmentFilePath))

    mailServer = None
    try:
        mailServer = smtplib.SMTP('smtp.gmail.com', 587)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(config.get_guser(), config.get_gpwd())
        mailServer.sendmail(
            config.get_guser(), 
            config.get_backupemail(), 
            msg.as_string())
    finally:
        if not mailServer is None:
            mailServer.close()

    print('    Sent email to %s' % config.get_backupemail())

def get_attachment(attachmentFilePath):
    contentType, encoding = mimetypes.guess_type(attachmentFilePath)
    
    if contentType is None or encoding is not None:
        contentType = 'application/octet-stream'
    
    mainType, subType = contentType.split('/', 1)
    
    #Add the attachment
    file = None
    try:
        file = open(attachmentFilePath, 'rb')
        attachment = MIMEBase(mainType, subType)
        attachment.set_payload(file.read())
        encode_base64(attachment)
    finally:
        if not file is None:
            file.close()
    
    attachment.add_header(
        'Content-Disposition', 
        'attachment',   
        filename=os.path.basename(attachmentFilePath))
    
    return attachment